<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\UserAction\RestorePasswordChance;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Jobs\StormSmsJob;
use Encore\Admin\Layout\Content;
use App\Admin\Tools\UserBatchSmsTool;
use App\Admin\Actions\UserAction\Orders;
use App\Admin\Actions\UserAction\Upgrades;
use App\Admin\Actions\UserAction\TeamOnes;
use App\Admin\Actions\UserAction\TeamTwos;
use App\Admin\Actions\UserAction\VipPurchase;
use App\Admin\Actions\UserAction\DismissMelt;
use App\Admin\Actions\UserAction\UserBalance;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\UserAction\UserGoldBeans;
use App\Admin\Actions\UserAction\SyncUserCache;
use App\Admin\Actions\UserAction\UserGoldCoins;
use App\Admin\Actions\UserAction\DismissPayCode;
use App\Admin\Actions\UserAction\SyncStormCache;
use App\Admin\Actions\UserAction\UserGoldRecords;
use App\Admin\Actions\UserAction\TransferGoldCoins;
use App\Admin\Actions\UserAction\TransferGoldBeans;
use App\Admin\Actions\UserAction\AlipayBindDismiss;
use App\Admin\Actions\UserAction\WechatBindDismiss;
use App\Admin\Actions\UserAction\TransferGoldCashes;
use App\Admin\Actions\UserAction\BankCardBindDismiss;
use App\Admin\Actions\UserAction\TransferGoldSubsidies;
use App\Admin\Actions\UserAction\TransferBalance;
use Illuminate\Support\Facades\Storage;

abstract class CommonUsersController extends AdminController
{
    protected $title = '会员列表';

    abstract protected function getType();
    abstract protected function customedGrid(Grid $grid);
    abstract protected function customedDetail($id);
    abstract protected function customedForm(Form $form);

    protected function getTeam(Grid $grid)
    {
	    if (request('level') == 1 and $userId = request('user_id')) {
		    $grid->model()->where('parent_id', $userId)->orderByDesc('id');
	    }
	    if (request('level') == 2 and $userId = request('user_id')) {
	    	$user = User::query()->find($userId);
		    $grid->model()->whereIn('parent_id', $user->myDownOneChildren()->pluck('id'))->orderByDesc('id');
	    }
    }

    protected function grid()
    {
        $grid = new Grid(new User());
	    $grid->model()->where("grade","vip")->orderByDesc('id');

	    //$this->getTeam($grid);

	    $grid->column('name', '商家')->display(function () {
		    return $this->nameText(true);
	    });
        
        $grid->column('phone', '手机');
       	
       	//  $grid->column('avatar', '商家门头')->display(function ($value) {
	       //  if (! Storage::exists($value)) {
		      //  // $this->update(['cover' => null]);
		      //   return '';
	       //  } else {
		      //   return _grid_image($value);
	       //  }
        // });

        $grid->column('business', '营业执照')->display(function ($value) {
	        if (! Storage::exists($value)) {
		       // $this->update(['cover' => null]);
		        return '';
	        } else {
		        return _grid_image($value);
	        }
        });

	    $grid->column('created_at', '创建时间')->display(function () {
		    return (string)$this->created_at;
	    });

        $grid->disableRowSelector();
        $grid->disableExport();

        $this->gridTools($grid);
        $this->gridFilter($grid);
        $this->gridActions($grid);

       // $this->customedGrid($grid);

        return $grid;
    }

    protected function gridTools(Grid $grid)
    {
	    $grid->tools(function (Grid\Tools $tools) {
	    	//$tools->append(new UserBatchSmsTool());
	    });
    }

    protected function gridFilter(Grid $grid)
    {
    	$grid->filter(function (Grid\Filter $filter) {

    		$filter->expand();

		    $filter->scope('normal', '普通会员')->where('grade', 'normal');
		    $filter->scope('vip', 'VIP会员')->where('grade', 'vip');

    		$filter->column(1/2, function (Grid\Filter $filter) {
    			$filter->disableIdFilter();
    			$filter->equal('id', 'ID 查询');
			    $filter->like('name', '昵称查询');
		    });

    		$filter->column(1/2, function (Grid\Filter $filter) {
			    $filter->equal('invite_code', '邀请码');
			    $filter->endsWith('phone', '手机号');
		    });
	    });
    }

    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	//$actions->disableDelete();
	    	/*$actions->add(new TransferBalance());*/
	    });
    }

    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

       
        $show->field('name', '商家名称');
        $show->field('avatar', '商家门头');
        $show->field('phone', '手机号');
        $show->field('business', '营业执照');
        $show->field('password', '密码');
        $show->field('created_at', '创建时间');
        $show->field('updated_at', '修改时间');

        $show->panel()->tools(function (Show\Tools $tools) {
        	$tools->disableDelete();
        });

        $this->customedDetail($id);

        return $show;
    }

   /* public function smsForm(Content $content)
    {
	    return $content->header('批量发送风暴活动短信')
		    ->body(view('admin.users.batchsms'));
    }*/

    public function smsStore()
    {
    	$state = request('state');
	    $phones = request('phones');
	    $phones = collect(explode("\r\n", $phones));

	    if (!in_array($state, [0,1])) {
		    admin_toastr('仅可发送风暴活动短信', 'error');
		    return redirect()->back();
	    }
	    if (empty($phones->first())) {
		    admin_toastr('请输入手机号码', 'error');
		    return redirect()->back();
	    }
	    if ($phones->count() > 500) {
		    admin_toastr('不可超过500条短信/次', 'error');
		    return redirect()->back();
	    }

	    $isSuccess = $state == 1 ? true : false;

	    foreach ($phones as $phone) {

	    	$phone = trim($phone);

	    	if (empty($phone)) continue;

		    if(preg_match("/^1[3456789]\d{9}$/", $phone)){
			    dispatch(new StormSmsJob($phone, $isSuccess));
		    }
	    }

	    admin_toastr('提交成功', 'success');
	    return redirect()->back();
    }

    protected function form()
    {
        $form = new Form(new User());

	    $form->text('name', '商家名称')->rules('required');
	    $form->text('phone', '登录手机号')->rules('required');

	    $form->image('avatar', '商家门头')
		    ->uniqueName()
		    ->creationRules('required');

		$form->image('business', '营业执照')
		    ->uniqueName();
		$form->latlong('latitude', 'longitude', 'Position')->height(500);
		$form->select('province_code','所在省')->options("/admin/api/provinces")->load('city_code', '/admin/api/areas');;
		$form->select('city_code','所在市');


        $this->formTools($form);
        $this->formSaving($form);

        return $form;
    }

    protected function formTools(Form $form)
    {
    	$form->tools(function (Form\Tools $tools) {
		    $tools->disableDelete();
	    });
    }

    protected function formSaving(Form $form)
    {
    	$form->saving(function (Form $form) {
		    // Passowrd for editing mode
    		if (empty($form->password)) {
		    	$form->password = $form->model()->getOriginal('password');
		    }
    		// Password for creating mode
		    else {
		    	$form->password = bcrypt($form->password);
		    }
	    });
    }
}
